package utils

import (
	"bytes"
	"crypto/cipher"

	"github.com/emmansun/gmsm/sm4"
)

func Encrypt(plainText []byte, key []byte, iv []byte) ([]byte, error) {
	block, err := sm4.NewCipher(key)
	if err != nil {
		return nil, err
	}

	// 填充原始数据
	blockSize := block.BlockSize()
	padding := blockSize - len(plainText)%blockSize
	padText := bytes.Repeat([]byte{byte(padding)}, padding)
	plainText = append(plainText, padText...)
	cipherText := make([]byte, len(plainText))

	mode := cipher.NewCBCEncrypter(block, iv)
	mode.CryptBlocks(cipherText, plainText)

	return cipherText, nil
}
